import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
import store from './store'
import { asyncRoutes } from '@/router'

NProgress.configure({
  showSpinner: false // 不显示右边圆环
})

// 白名单
const whiteList = ['/login']

/**
 * 路由全局前置守卫
 */
router.beforeEach(async(to, from, next) => {
  // 1.开启进度条
  NProgress.start()
  // 2. 获取token
  const token = store.getters.token
  // 3. 判断
  if (token) {
    // 3.1 如果是去登录页, 拦截去首页
    if (to.path === '/login') {
      next('/')
      // 细节: 一旦拦截就不会进入后置守卫
      NProgress.done()
    } else {
      if (!store.getters.userInfo?.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }

      next()
    }
  } else {
    // 3.2 判断是否在白名单中
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

/**
 * 路由全局后置守卫
 */
router.afterEach(() => {
  // 1. 关闭进度条
  NProgress.done()
})
